package com.lsh.oms.core.dao.mybatis.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import static com.lsh.oms.core.dao.mybatis.Json.fromJson;
import static com.lsh.oms.core.dao.mybatis.Json.toJson;

@MappedTypes(List.class)
public class JsonListHandler implements TypeHandler<List<Object>> {
    static TypeReference<List<Object>> ARRAY_JSON_TYPE = new TypeReference<List<Object>>() {

    };

    @Override
    public void setParameter(PreparedStatement ps, int i, List<Object> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter != null ? toJson(parameter) : null);
    }

    @Override
    public List<Object> getResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getString(columnName) != null ? fromJson(rs.getBlob(columnName), ARRAY_JSON_TYPE) : null;
    }

    @Override
    public List<Object> getResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getString(columnIndex) != null ? fromJson(rs.getBlob(columnIndex), ARRAY_JSON_TYPE) : null;
    }

    @Override
    public List<Object> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getString(columnIndex) != null ? fromJson(cs.getBlob(columnIndex), ARRAY_JSON_TYPE) : null;
    }
}
